package com.example.controller;

import com.example.model.ChatMessage;
import com.example.service.ChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 聊天控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@Tag(name = "聊天管理", description = "聊天消息相关接口")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping("/send")
    @Operation(summary = "发送聊天消息")
    public ResponseEntity<Map<String, Object>> sendMessage(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        
        try {
            String senderId = authentication.getName();
            String receiverId = (String) request.get("receiverId");
            String content = (String) request.get("content");
            String messageTypeStr = (String) request.get("messageType");
            String extraData = (String) request.get("extraData");

            ChatMessage.MessageType messageType = ChatMessage.MessageType.TEXT;
            if (messageTypeStr != null) {
                messageType = ChatMessage.MessageType.valueOf(messageTypeStr.toUpperCase());
            }

            ChatMessage message = chatService.sendMessage(senderId, receiverId, content, messageType, extraData);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "消息发送成功");
            response.put("data", message);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("发送消息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "发送消息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/history/{userId}")
    @Operation(summary = "获取聊天历史记录")
    public ResponseEntity<Map<String, Object>> getChatHistory(
            @PathVariable String userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            Authentication authentication) {
        
        try {
            String currentUserId = authentication.getName();
            Page<ChatMessage> messages = chatService.getChatHistory(currentUserId, userId, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", messages);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取聊天历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取聊天历史失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/partners")
    @Operation(summary = "获取聊天对话列表")
    public ResponseEntity<Map<String, Object>> getChatPartners(Authentication authentication) {
        try {
            String userId = authentication.getName();
            List<String> partners = chatService.getChatPartners(userId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", partners);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取聊天对话列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取聊天对话列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/unread-count")
    @Operation(summary = "获取未读消息数量")
    public ResponseEntity<Map<String, Object>> getUnreadMessageCount(Authentication authentication) {
        try {
            String userId = authentication.getName();
            Long count = chatService.getUnreadMessageCount(userId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", count);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取未读消息数量失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/unread-count/{userId}")
    @Operation(summary = "获取与指定用户的未读消息数量")
    public ResponseEntity<Map<String, Object>> getUnreadMessageCountBetween(
            @PathVariable String userId,
            Authentication authentication) {
        
        try {
            String currentUserId = authentication.getName();
            Long count = chatService.getUnreadMessageCountBetween(userId, currentUserId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", count);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取未读消息数量失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/read/{messageId}")
    @Operation(summary = "标记消息为已读")
    public ResponseEntity<Map<String, Object>> markMessageAsRead(@PathVariable Long messageId) {
        try {
            chatService.markMessageAsRead(messageId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "标记成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("标记消息已读失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "标记消息已读失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/read-batch")
    @Operation(summary = "批量标记消息为已读")
    public ResponseEntity<Map<String, Object>> markMessagesAsRead(@RequestBody List<Long> messageIds) {
        try {
            chatService.markMessagesAsRead(messageIds);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量标记成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("批量标记消息已读失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "批量标记消息已读失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/read-all/{userId}")
    @Operation(summary = "标记与指定用户的所有消息为已读")
    public ResponseEntity<Map<String, Object>> markAllMessagesAsReadBetween(
            @PathVariable String userId,
            Authentication authentication) {
        
        try {
            String currentUserId = authentication.getName();
            chatService.markAllMessagesAsReadBetween(userId, currentUserId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "标记成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("标记所有消息已读失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "标记所有消息已读失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/message/{messageId}")
    @Operation(summary = "获取消息详情")
    public ResponseEntity<Map<String, Object>> getMessageById(@PathVariable Long messageId) {
        try {
            Optional<ChatMessage> messageOpt = chatService.getMessageById(messageId);
            
            Map<String, Object> response = new HashMap<>();
            if (messageOpt.isPresent()) {
                response.put("success", true);
                response.put("data", messageOpt.get());
            } else {
                response.put("success", false);
                response.put("message", "消息不存在");
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取消息详情失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取消息详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/service-inquiry")
    @Operation(summary = "发送服务咨询消息")
    public ResponseEntity<Map<String, Object>> sendServiceInquiry(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        
        try {
            String senderId = authentication.getName();
            String receiverId = (String) request.get("receiverId");
            String content = (String) request.get("content");
            Long serviceId = Long.valueOf(request.get("serviceId").toString());

            ChatMessage message = chatService.sendServiceInquiry(senderId, receiverId, content, serviceId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "咨询消息发送成功");
            response.put("data", message);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("发送服务咨询失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "发送服务咨询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/order-inquiry")
    @Operation(summary = "发送订单咨询消息")
    public ResponseEntity<Map<String, Object>> sendOrderInquiry(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        
        try {
            String senderId = authentication.getName();
            String receiverId = (String) request.get("receiverId");
            String content = (String) request.get("content");
            Long orderId = Long.valueOf(request.get("orderId").toString());

            ChatMessage message = chatService.sendOrderInquiry(senderId, receiverId, content, orderId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "订单咨询发送成功");
            response.put("data", message);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("发送订单咨询失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "发送订单咨询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
